import { getInfo, getUserDetailById, login } from '@/api/user'
import { getToken, removeToken, setToken } from '@/utils/auth'

export default {
  namespaced: true,
  state: {
    token: getToken() || '',
    userInfo: ''
  },
  mutations: {
    updataToken(state, payload) {
      state.token = payload
      // 本地化储存
      setToken(payload)
    },
    updateUserInfo(state, payload) {
      state.userInfo = payload
    },
    removeUser(state) {
      state.userInfo = {}
    },
    removeToken(state) {
      state.token = ''
      removeToken()
    }
  },
  actions: {
    async userLogin(context, payload) {
      const res = await login(payload)
      // 储存 token
      context.commit('updataToken', res.data)
      return res
    },
    async getuserInfo(context, payload) {
      const res = await getInfo()
      // 2. 根据用户id（rs.data.userId）再发请求，获取详情（包含头像）
      const info = await getUserDetailById(res.data.userId)

      context.commit('updateUserInfo', { ...info.data, ...res.data })
    },
    logout(context) {
      context.commit('removeToken')
      context.commit('removeUser')
    }
  },
  getters: {}
}
